package com.tanhua.dubbo.server.api;

import cn.hutool.core.lang.UUID;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.Method;
import cn.hutool.json.JSONException;
import cn.hutool.json.JSONUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.dubbo.server.config.HuanXinConfig;
import com.tanhua.dubbo.server.enums.HuanXinMessageType;
import com.tanhua.dubbo.server.mapper.HuanXinUserMapper;
import com.tanhua.dubbo.server.pojo.HuanXinUser;
import com.tanhua.dubbo.server.service.RequestService;
import com.tanhua.dubbo.server.service.TokenService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Arrays;
import java.util.Date;

@Slf4j
@Service(version = "1.0.0")
public class HuanXinApiImpl implements HuanXinApi {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private HuanXinConfig huanXinConfig;

    @Autowired
    private RequestService requestService;

    @Autowired
    private HuanXinUserMapper huanXinUserMapper;

    /**
     * 获取环信中生成的token
     *
     * @return
     */
    @Override
    public String getToken() {
        return tokenService.getToken();
    }

    /**
     * 注册环信用户
     *
     * @param userId
     * @return
     */
    @Override
    public Boolean register(Long userId) {
        String url = huanXinConfig.getUrl() + huanXinConfig.getOrgName() + "/" + huanXinConfig.getAppName() + "/users";
        HuanXinUser huanXinUser = new HuanXinUser();
        huanXinUser.setUsername("HX_" + userId);
        huanXinUser.setPassword(UUID.randomUUID().toString(true));

        HttpResponse response = requestService.excute(url, JSONUtil.toJsonStr(Arrays.asList(huanXinUser)), Method.POST);
        if (response.isOk()) {
            huanXinUser.setUserId(userId);
            huanXinUser.setCreated(new Date());
            huanXinUser.setUpdated(huanXinUser.getCreated());

            huanXinUserMapper.insert(huanXinUser);
            return true;
        }
        return false;
    }

    /**
     * 通过当前登录用户的ID查找在环信中注册的用户信息
     *
     * @param userId
     * @return
     */
    @Override
    public HuanXinUser findHuanXinUser(Long userId) {
        QueryWrapper<HuanXinUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        return huanXinUserMapper.selectOne(queryWrapper);
    }

    /**
     * 通过环信用户名查询用户信息
     *
     * @param username
     * @return
     */
    @Override
    public HuanXinUser findUserByHuanXinUserName(String username) {
        QueryWrapper<HuanXinUser> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("username", "HX_"+username);
        return huanXinUserMapper.selectOne(queryWrapper);
    }

    /**
     * 添加环信中的好友关系(双向好友关系)
     *
     * @param id
     * @param friendId
     * @return
     */
    @Override
    public boolean addFriend(Long id, Long friendId) {
        String url = huanXinConfig.getUrl() + huanXinConfig.getOrgName() + "/" + huanXinConfig.getAppName()
                + "/users/HX_" + id + "/contacts/users/HX_" + friendId;

        try {
            // 404 -> 对方未在环信注册
            HttpResponse response = requestService.excute(url, null, Method.POST);
            return response.isOk();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //添加失败
        return false;
    }

    /**
     * 在环信中取消好友关系(双向取消)
     *
     * @param userId
     * @param friendId
     * @return
     */
    @Override
    public boolean removeFriend(Long userId, Long friendId) {
        String url = huanXinConfig.getUrl() + huanXinConfig.getOrgName() + "/" + huanXinConfig.getAppName()
                + "/users/HX_" + userId + "/contacts/users/HX_" + friendId;
        try {
            HttpResponse response = requestService.excute(url, null, Method.DELETE);
            return response.isOk();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 以管理员身份发送消息
     *
     * @param targetUserName     发送目标的用户名
     * @param huanXinMessageType 消息类型
     * @param msg
     * @return
     */
    @Override
    public boolean answerQuestion(String targetUserName, HuanXinMessageType huanXinMessageType, String msg) {
        String url = huanXinConfig.getUrl() + huanXinConfig.getOrgName() + "/" + huanXinConfig.getAppName() + "/messages";
        try {
            //{"target_type": "users","target": ["user2","user3"],
            //"msg": {"type": "txt","msg": "testmessage"},"from": "user1"}
            String body = JSONUtil.createObj().set("target_type", "users")
                    .set("target", JSONUtil.createArray().set(targetUserName))
                    .set("msg", JSONUtil.createObj().set("type", huanXinMessageType.getType())
                                                    .set("msg",msg)).toString();
            //表示消息发送者;无此字段Server会默认设置为“from”:“admin”，有from字段但值为空串(“”)时请求失败
            //.set("from", "")
            HttpResponse response = requestService.excute(url, body, Method.POST);
            if(response.isOk()){
                return true;
            }
        } catch (JSONException e) {
            log.error("发送消息失败~ targetUserName = " + targetUserName+", type = " + huanXinMessageType.getType()+", msg = " + msg, e);
        }
        return false;
    }
}
